<template>
  <view>
    <s-layout :onShareAppMessage="shareInfo" navbar="goods">
      <!-- 标题栏 -->
      <detailNavbar />

      <!-- 骨架屏 -->
      <detailSkeleton v-if="state.skeletonLoading" />
      <!-- 下架/售罄提醒 -->
      <s-empty
        v-else-if="state.goodsInfo === null"
        text="商品不存在或已下架"
        icon="/static/soldout-empty.png"
        showAction
        actionText="再逛逛"
        actionUrl="/pages/goods/list"
      />
      <block v-else>
        <view class="detail-swiper-selector">
          <!-- 商品轮播图  -->
          <su-swiper
            class="ss-m-b-14"
            isPreview
            :list="formatGoodsSwiper(state.goodsInfo.sliderPicUrls)"
            otStyle="tag"
            imageMode="widthFix"
            dotCur="bg-mask-40"
            :seizeHeight="750"
          />

          <!-- 价格标题卡片 -->
          <view class="detail-card title-card ss-flex-col">
            <view class="price-box ss-flex ss-col-bottom ss-m-b-20">
              <view class="price-text">{{ fen2yuan(state.goodsInfo.price) }}</view>
              <view
                class="origin-price-text ss-flex ss-col-bottom"
                v-if="state.goodsInfo.marketPrice"
              >
                {{ fen2yuan(state.goodsInfo.marketPrice) }}
              </view>
            </view>
            <view class="title-text ss-line-2 ss-m-b-6">{{ state.goodsInfo.name }}</view>
            <view class="subtitle-text ss-line-1">{{ state.goodsInfo.introduction }}</view>
          </view>

          <!-- 功能卡片 -->
          <view class="detail-cell-card detail-card ss-flex-col">
            <detail-cell-sku :sku="state.selectedSku" @tap="state.showSelectSku = true" />
          </view>

          <!-- 规格与数量弹框 -->
          <s-select-sku
            :goodsInfo="state.goodsInfo"
            :show="state.showSelectSku"
            @buy="onBuy"
            @addCart="onAddCart"
            @change="onSkuChange"
            @close="state.showSelectSku = false"
          />
        </view>

        <!-- 详情 -->
        <detail-content-card
          class="detail-content-selector"
          :content="state.goodsInfo.description"
        />
      </block>

      <!-- 底部操作栏 -->
      <detail-tabbar
        v-if="!isEmpty(state.goodsInfo)"
        v-model="state.goodsInfo"
        :goodsId="state.goodsInfo.id"
        :goodsInfo="state.goodsInfo"
        :sku="state.selectedSku"
        @buy="onBuy"
        @addCart="onAddCart"
        @selectSku="state.showSelectSku = true"
      >
        <view class="buy-box ss-flex ss-col-center ss-p-r-20" v-if="state.goodsInfo.stock > 0">
          <button
            class="ss-reset-button add-btn ui-Shadow-Main"
            @tap="state.showSelectSku = true"
          >
            加入购物车
          </button>
          <button
            class="ss-reset-button buy-btn ui-Shadow-Main"
            @tap="state.showSelectSku = true"
          >
            立即购买
          </button>
        </view>
        <view class="buy-box ss-flex ss-col-center ss-p-r-20" v-else>
          <button class="ss-reset-button disabled-btn" disabled> 已售罄 </button>
        </view>
      </detail-tabbar>
    </s-layout>
  </view>
</template>

<script setup>
import { reactive, computed } from 'vue';
import { onLoad, onPageScroll } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import { isEmpty } from 'lodash-es';
import { fen2yuan, formatGoodsSwiper } from '@/sheep/hooks/useGoods';
import detailNavbar from './components/detail/detail-navbar.vue';
import detailCellSku from './components/detail/detail-cell-sku.vue';
import detailTabbar from './components/detail/detail-tabbar.vue';
import detailSkeleton from './components/detail/detail-skeleton.vue';
import detailContentCard from './components/detail/detail-content-card.vue';
import SpuApi from '@/sheep/api/product/spu';
import FavoriteApi from '@/sheep/api/product/favorite';
import OrderApi from '@/sheep/api/trade/order';

const headerBg = sheep.$url.css('/static/img/shop/goods/goods-bg.png');
const statusBarHeight = sheep.$platform.device.statusBarHeight * 2;

const isLogin = computed(() => sheep.$store('user').isLogin);

const state = reactive({
  goodsId: 0,
  skeletonLoading: true, // SPU 加载中
  goodsInfo: {}, // SPU 信息
  showSelectSku: false, // 是否展示 SKU 选择弹窗
  selectedSku: {}, // 选中的 SKU
  settlementSku: {}, // 结算的 SKU
  showModel: false, // 是否展示 Coupon 优惠劵的弹窗
  couponInfo: [], // 可领取的 Coupon 优惠劵的列表
  showActivityModel: false, // 是否展示 Activity 营销活动的弹窗
  rewardActivity: {}, // 【满减送】活动
  activityList: [], // 【秒杀/拼团/砍价】可参与的 Activity 营销活动的列表
});

// 规格变更
function onSkuChange(e) {
  state.selectedSku = e;
  state.settlementSku = e;
}

// 添加购物车
function onAddCart(e) {
  if (!e.id) {
    sheep.$helper.toast('请选择商品规格');
    return;
  }
  sheep.$store('cart').add(e);
}

// 立即购买
function onBuy(e) {
  if (!e.id) {
    sheep.$helper.toast('请选择商品规格');
    return;
  }
  sheep.$router.go('/pages/order/confirm', {
    data: JSON.stringify({
      items: [
        {
          skuId: e.id,
          count: e.goods_num,
          categoryId: state.goodsInfo.categoryId,
        },
      ],
    }),
  });
}

// 获取结算信息
async function getSettlementByIds(spuIds) {
  const { data } = await OrderApi.getSettlementProduct(spuIds);
  if (data.length === 0) {
    return;
  }
  const spu = data[0];
  state.settlementSku = spu.skus[0] || {};
}

// 分享信息
const shareInfo = computed(() => {
  if (isEmpty(state.goodsInfo)) return {};
  return sheep.$platform.share.getShareInfo(
    {
      title: state.goodsInfo.name,
      desc: state.goodsInfo.introduction,
      image: sheep.$url.cdn(state.goodsInfo.picUrl),
      params: {
        page: '2',
        query: state.goodsId,
      },
    },
    {
      type: 'goods',
      title: state.goodsInfo.name,
      image: sheep.$url.cdn(state.goodsInfo.picUrl),
    },
  );
});

onLoad((options) => {
  // 非法参数
  if (!options.id) {
    state.goodsInfo = null;
    state.skeletonLoading = false;
    return;
  }
  state.goodsId = options.id;
  
  // 加载商品信息
  SpuApi.getSpuDetail(state.goodsId).then((res) => {
    if (res.code !== 0 || !res.data) {
      state.goodsInfo = null;
      state.skeletonLoading = false;
      return;
    }
    // 加载到商品
    state.skeletonLoading = false;
    state.goodsInfo = res.data;
    // 获取结算信息
    getSettlementByIds(state.goodsId);
    // 加载是否收藏
    if (isLogin.value) {
      FavoriteApi.isFavoriteExists(state.goodsId).then((res) => {
        if (res.code !== 0) {
          return;
        }
        state.goodsInfo.favorite = res.data;
      });
    }
  });
});
</script>

<style lang="scss" scoped>
.detail-card {
  background-color: $white;
  margin: 14rpx 20rpx;
  border-radius: 10rpx;
  overflow: hidden;
}

.title-card {
  padding: 30rpx;
}

.price-box {
  .price-text {
    font-size: 42rpx;
    font-weight: 500;
    color: $red;
    
    &::before {
      content: '¥';
      font-size: 30rpx;
    }
  }
  
  .origin-price-text {
    font-size: 26rpx;
    color: $gray-c;
    text-decoration: line-through;
    margin-left: 16rpx;
    
    &::before {
      content: '¥';
    }
  }
}

.title-text {
  font-size: 30rpx;
  font-weight: 500;
  line-height: 42rpx;
}

.subtitle-text {
  font-size: 26rpx;
  color: $gray-b;
  line-height: 42rpx;
}

// 购买按钮样式
.buy-box {
  .add-btn {
    width: 214rpx;
    height: 72rpx;
    font-weight: 500;
    font-size: 28rpx;
    border-radius: 40rpx 0 0 40rpx;
    background-color: var(--ui-BG-Main-light);
    color: var(--ui-BG-Main);
  }

  .buy-btn {
    width: 214rpx;
    height: 72rpx;
    font-weight: 500;
    font-size: 28rpx;
    border-radius: 0 40rpx 40rpx 0;
    background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
    color: $white;
  }

  .disabled-btn {
    width: 428rpx;
    height: 72rpx;
    border-radius: 40rpx;
    background: #999999;
    color: $white;
    font-weight: 500;
    font-size: 28rpx;
  }
}
</style>
